<template>
    <div class="app-container">
        <el-row :gutter="20" class="div-height-left">
            <!--用户数据-->
            <el-col :span="24" :xs="24" class="div-height-left">
                <el-row>
                    <el-col :span="7">
                        <div class="search-container">
                            <el-form v-show="showSearch" ref="queryParamsRef" :inline="true" :model="queryParams"
                                label-width="80px">
                                <el-form-item v-if="!userInfo.orgId" label="机构" prop="orgId" style="width: 47%;">
                                    <select-org-tree :value="queryParams.orgId" @orgNodeClick="orgNodeClick" />
                                </el-form-item>
                                <el-form-item label="类型名称" prop="name" style="width: 40%;">
                                    <el-input v-model="queryParams.name" clearable placeholder="请输入类型名称"
                                        @keyup.enter.native="handleQuery" />
                                </el-form-item>
                                <el-form-item style="width: 100%">
                                    <query-form-button @handleQuery="handleQuery" @resetQuery="resetQuery" />
                                </el-form-item>
                            </el-form>
                        </div>
                        <el-row :gutter="10" class="mb8">
                            <el-col :span="1.5">
                                <el-button v-hasPerm="['base:labType:add']" plain type="primary"
                                    @click="handleAdd"><template #icon><i-ep-plus /></template>新增类型
                                </el-button>
                            </el-col>
                            <el-col :span="1.5">
                                <el-button plain type="info" @click="toggleExpandAll"><template
                                        #icon><i-ep-sort /></template>展开/折叠
                                </el-button>
                            </el-col>
                        </el-row>

                        <el-table v-if="refreshTable" v-adaptive="40" :data="labTypeList"
                            :default-expand-all="isExpandAll" highlight-current-row
                            :header-cell-style="$headerCellStyle"
                            :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" :border="true"
                            row-key="labTypeId" stripe style="overflow-y: auto;" @row-click="rowClick">
                            <el-table-column :show-overflow-tooltip="true" label="类型名称" prop="name" width="130px" />
                            <!--            <el-table-column label="执行科室" :align="'center'" prop="performedBy"/>-->
                            <el-table-column :align="'center'" label="级别" prop="level" width="70px" />
                            <el-table-column :align="'center'" label="排序" prop="sort" width="70px" />
                            <el-table-column :align="'center'" class-name="small-padding fixed-width" fixed="right"
                                label="操作" min-width="100px">
                                <template #default="scope">
                                    <el-button v-hasPerm="['base:labType:edit']" type="success"
                                        @click.stop="handleUpdate(scope.row)"><template #icon><i-ep-edit /></template>修改
                                    </el-button>
                                    <el-button v-hasPerm="['base:labType:add']" type="primary"
                                        @click.stop="handleAdd(scope.row)"><template #icon><i-ep-plus /></template>新增
                                    </el-button>
                                    <el-button v-hasPerm="['base:labType:remove']" type="danger"
                                        @click.stop="handleDelete(scope.row)"><template
                                            #icon><i-ep-delete /></template>删除
                                    </el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-col>
                    <el-col :span="17">
                        <lab-vs-clinic ref="labVsClinicRef" :org-id="queryParams.orgId" />
                    </el-col>
                </el-row>
            </el-col>
        </el-row>

        <!-- 添加或修改检验项目类型lab_type对话框 -->
        <el-dialog :close-on-click-modal="false" :title="title" v-model="open" append-to-body width="500px">
            <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
                <el-form-item label="类型名称" prop="name">
                    <el-input v-model="form.name" placeholder="请输入类型名称" />
                </el-form-item>
                <!--                <el-form-item label="执行科室" prop="performedBy">-->
                <!--                    <el-input v-model="form.performedBy" placeholder="请输入执行科室"/>-->
                <!--                </el-form-item>-->
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="排序" prop="sort">
                            <el-input v-model="form.sort" placeholder="请输入排序" type="number" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="级别" prop="level">
                            <el-input v-model="form.level" disabled placeholder="请输入级别" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-form-item label="备注信息" prop="remarks">
                    <el-input v-model="form.remarks" placeholder="请输入备注信息" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup>
import {addLabType, delLabType, getLabType, listLabType, updateLabType} from "@/api/base/labType";
import labVsClinic from "@/views/base/labType/labVsClinic.vue";
import {useUserStoreHook} from "@/store/modules/user";

const useUserStore = useUserStoreHook();
const { proxy } = getCurrentInstance() as any
const formRef = ref()
const labVsClinicRef = ref()
// 登录用户信息
const userInfo = <UserInfoBusi>useUserStore.user.userInfo
// 按钮loading
const buttonLoading = ref(false)
// 下拉框机构树
const orgOptions = ref([])
// 显示搜索条件
const showSearch = ref(true)
// 检验项目类型lab_type表格数据
const labTypeList = ref<any>([])
// 检验项目类型lab_type树选项
const labTypeOptions = ref<any>([])
// 检验类型list（无父子结构）
const typeList = ref([])
// 弹出层标题
const title = ref("")
// 是否显示弹出层
const open = ref(false)
// 是否展开，默认全部展开
const isExpandAll = ref(true)
// 重新渲染表格状态
const refreshTable = ref(true)
// 查询参数
const queryParamsRef = ref()
const queryParams = ref({
    name: "",
    orgId: "",
    performedBy: "",
    sort: "",
    level: "",
    parentId: "",
    parentIds: "",
    remarks: ""
})
// 表单参数
const form = ref<any>({})
// 表单校验
const rules = ref({
    name: [
        {
            required: true, message: "类型名称不能为空", trigger: "blur"
        }
    ],
    orgId: [
        {
            required: true, message: "机构ID不能为空", trigger: "blur"
        }
    ],
    sort: [
        {
            required: true, message: "排序不能为空", trigger: "blur"
        }
    ],
    level: [
        {
            required: true, message: "级别不能为空", trigger: "blur"
        }
    ],
})

if (userInfo.orgId) {
    queryParams.value.orgId = userInfo.orgId
    getList()
}
/** 查询检验项目类型lab_type列表 */
function getList() {
    listLabType(queryParams.value).then((response: any) => {
        typeList.value = response.data
        labTypeList.value = proxy.$handleTree(response.data, "labTypeId", "parentId");
    });
}
// 机构树点击事件
function orgNodeClick(data, _e) {
    queryParams.value.orgId = data.orgId
    if (queryParams.value.orgId) {
        getList()
    }
}
/** 查询检验项目类型lab_type下拉树结构 */
function getTreeselect() {
    listLabType({ orgId: queryParams.value.orgId }).then((response: any) => {
        labTypeOptions.value = [];
        const data: any = { labTypeId: 0, name: '顶级节点', children: [], level: '0' };
        data.children = proxy.$handleTree(response.data, "labTypeId", "parentId");
        labTypeOptions.value.push(data);
    });
}
// 取消按钮
function cancel() {
    open.value = false;
    reset();
}
// 表单重置
function reset() {
    form.value = {
        labTypeId: null,
        name: null,
        orgId: queryParams.value.orgId,
        performedBy: null,
        sort: null,
        level: null,
        parentId: null,
        parentIds: null,
        delFlag: null,
        createBy: null,
        updateBy: null,
        remarks: null
    };
}
/** 搜索按钮操作 */
function handleQuery() {
    getList();
}
/** 重置按钮操作 */
function resetQuery() {
    queryParamsRef.value.resetFields()
    handleQuery();
}
/** 新增按钮操作 */
function handleAdd(row) {
    reset();
    getTreeselect();
    if (row != null && row.labTypeId) {
        form.value.parentId = row.labTypeId;
        form.value.level = Number(row.level) + 1
    } else {
        form.value.parentId = 0;
        form.value.level = 1;
    }
    open.value = true;
    title.value = "添加检验项目类型";
}
/** 展开/折叠操作 */
function toggleExpandAll() {
    refreshTable.value = false;
    isExpandAll.value = !isExpandAll.value;
    nextTick(() => {
        refreshTable.value = true;
    });
}
/** 修改按钮操作 */
function handleUpdate(row) {
    reset();
    getTreeselect();
    if (row != null) {
        form.value.parentId = row.labTypeId;
    }
    getLabType(row.labTypeId).then(response => {
        form.value = response.data;
        open.value = true;
        title.value = "修改检验项目类型";
    });
}
/** 提交按钮 */
function submitForm() {
    (formRef.value as any).validate(valid => {
        if (valid) {
            buttonLoading.value = true;
            let index = typeList.value.findIndex((item: any) => {
                return item.name === form.value.name
            })
            // if ((index > -1 && form.value.labTypeId !== typeList.value[index].labTypeId)
            //     || (index > -1 && !form.value.labTypeId)) {
            //     buttonLoading.value = false;
            //     return ElMessage.error("类别名称已存在，请重新修改类别名称")
            // }
            if (form.value.labTypeId != null) {
                updateLabType(form.value).then(_response => {
                    ElMessage.success("修改成功");
                    open.value = false;
                    getList();
                }).finally(() => {
                    buttonLoading.value = false;
                });
            } else {
                addLabType(form.value).then(_response => {
                    ElMessage.success("新增成功");
                    open.value = false;
                    getList();
                }).finally(() => {
                    buttonLoading.value = false;
                });
            }
        }
    });
}
/** 删除按钮操作 */
function handleDelete(row) {
    let type = true
    let index = labTypeList.value.findIndex((item: any) => {
        return row.labTypeId === item.labTypeId
    })
    if (index > -1) {
        if (labTypeList.value[index].children.length > 0) {
            type = false
        }
    }
    ElMessageBox.confirm('是否确认删除检验项目类型名称为"' + row.name + '"的数据项？',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        if (type) {
            delLabType(row.labTypeId).then(() => {
                if (type) {
                    getList();
                    ElMessage.success("删除成功");
                } else {
                    type = true
                    return ElMessage.error("此类别存在子项目，不能删除")
                }
            })
        }
    }).catch(() => {
    })
}
/** 类别列表行点击事件 */
function rowClick(row) {
    // 调用项目页面查询方法
  console.log("row",row)
    labVsClinicRef.value.init(row, typeList.value)
}
</script>
<script lang="ts">
export default {
    name: "LabType"
}
</script>
